<template>
  <div class="upload-img">
    <el-upload
      :accept="accept"
      :action="fileUpload"
      :before-remove="beforeRemove"
      :before-upload="beforeUpload"
      :file-list="fileList"
      :limit="limit"
      :on-exceed="handleExceed"
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      :on-success="handleSuccess"
      class="upload-demo"
      list-type="picture-card"
      name="files"
    >
      <i class="el-icon-plus"></i>
    </el-upload>
    <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过1M</div>
    <el-dialog :visible.sync="dialogVisible">
      <img :src="dialogImageUrl" alt width="100%" />
    </el-dialog>
  </div>
</template>


<script>
import {
  $fileUpload,
  $fileDownload,
  $thumbnailDownload
} from '@/api/common/adjunctApi'
export default {
  name: 'UploadImg',
  props: {
    limit: Number,
    adjuncts: Array
  },
  data() {
    return {
      accept: 'image/jpeg,image/png',
      fileUpload: $fileUpload,
      dialogImageUrl: '',
      dialogVisible: false
    }
  },
  computed: {
    fileList() {
      var tempArr = []
      for (const item of this.adjuncts) {
        var itemObj = JSON.parse(item)
        var tempObj = {}
        tempObj.name = itemObj.title + '.' + itemObj.prefix
        tempObj.url = $fileDownload + '/' + itemObj.id
        tempArr.push(tempObj)
      }
      return tempArr
    }
  },
  methods: {
    handleSuccess(res, file) {
      this.$emit('handleUploadImgRes', res)
    },
    beforeUpload(file) {
      var canUpload = true
      if (!this.judgeType(file)) {
        this.$message.error('上传图片只能是 jpg/png 格式!')
        canUpload = false
      } else if (this.judgeSize(file)) {
        this.$message.error('上传图片大小不能超过 1MB!')
        canUpload = false
      }
      return canUpload
    },
    handleExceed(files, fileList) {
      this.$message.warning(`只能上传${this.limit}张图片`)
    },
    beforeRemove(file, fileList) {
    },
    handleRemove(file, fileList) {
      this.$emit('handleRemoveImg')
    },
    handlePreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    //判断文件类型
    judgeType(file) {
      var isImg = true
      if (file.type != 'image/jpeg' && file.type != 'image/png') {
        isImg = false
      }
      return isImg
    },
    //判断文件大小
    judgeSize(file) {
      var isBig = false
      if (file.size / 1024 / 1024 > 1) {
        isBig = true
      }
      return isBig
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
